package com.situ.mall.base.handler;


import com.situ.mall.base.exception.InfoException;
import com.situ.mall.base.exception.NoLoginException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: MyException
 * Package: com.situ.store.handler
 * Description:
 *
 * @Author Darling_达
 * @Create 2023-03-08 15:55
 * @Version 1.0
 */

// 异常处理器
// 类似于Controller的思想，不考虑地址，一出异常就进这个handler
// 定义一个统一的异常处理器类添加@ControllerAdvice注解
// 每一个方法上添加@ExceptionHandler注解，指定哪种类型的异常执行此方法
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(NoLoginException.class)
    public ResponseEntity<?> handler5(NoLoginException noLoginException) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
    }

    @ExceptionHandler(InfoException.class)
    public ResponseEntity<?> handler4(InfoException businessException) {
        Map<String, String> map = new HashMap<>();
        map.put("msg", businessException.getMsg());
        return ResponseEntity.status(businessException.getCode()).body(map);
    }

    // 某某 1异常   方法 1
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handle1(RuntimeException runtimeException) {
        runtimeException.printStackTrace();
        Map<String, String> map = new HashMap<>();
        map.put("msg", "出运行时异常了");
//        return ResponseEntity.status(500).body(map);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
    }

    // 某某 2 异常  方法 2
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<Map<String, String>> handle2(NullPointerException nullPointerException) {
        nullPointerException.printStackTrace();
        Map<String, String> map = new HashMap<>();
        map.put("msg", "出现空指针异常了");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
    }

    // 某某 3 异常  方法 3
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, String>> handle3(Exception exception) {
        exception.printStackTrace();
        Map<String, String> map = new HashMap<>();
        map.put("msg", "服务器内部处理错误，请稍后再试");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
    }

}
